const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()

const views = require('koa-views')
// const co = require('co')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const debug = require('debug')('koa2:server')
const path = require('path')
const cors = require('koa2-cors')
const koaJwt = require('koa-jwt')
const session = require('koa-session');
const config = require('./config')
const routes = require('./routes')
let routerResponse = require('./middleware/routerResponse')

// 配置全局mysql
// const eqMysql = require('eq-mysql');
// eqMysql.config({
//      host: config.database.HOST,
//      database: config.database.DATABASE,
//      user: config.database.USERNAME,
//      password: config.database.PASSWORD,
//      port: config.database.PORT
// })


const port = process.env.PORT || config.port

// error handler
onerror(app)

app.keys = ['562'];
const sessionConfig = {
  key: 'using',
  maxAge: 86400000,
  autoCommit: true, /** (boolean) automatically commit headers (default true) */
  overwrite: true, /** (boolean) can overwrite or not (default true) */
  httpOnly: true, /** (boolean) httpOnly or not (default true) */
  signed: true, /** (boolean) signed or not (default true) */
  rolling: false, /** (boolean) Force a session identifier cookie to be set on every response. The expiration is reset to the original maxAge, resetting the expiration countdown. (default is false) */
  renew: false, /** (boolean) renew session when session is nearly expired, so we can always keep user logged in. (default is false)*/
  secure: false, /** (boolean) secure cookie*/
  sameSite: null, /** (string) session cookie sameSite options (default null, don't set it) */
};
app.use(session(sessionConfig, app));

// middlewares
app.use(bodyparser())
  .use(async (ctx, next) => {
    // ctx.cookies.set('token', 'token', {  maxAge: 86400000 })
    let token = (ctx.cookies.get('token') || '')
    if (token) {
      ctx.request.header.authorization = 'Bearer ' + token
    }
    await next()
  })
  .use(koaJwt({ secret: config.tokenSerect }).unless({
    path: [
      /^\/login/,
      //  /.*/匹配所有路由都不验证token
      /.*/
    ]
  }))
  .use(cors())
  .use(json())
  .use(logger()) // 打印请求日志
  .use(require('koa-static')(__dirname + '/public'))
  .use(views(path.join(__dirname, '/views'), {
    options: { settings: { views: path.join(__dirname, 'views') } },
    map: { 'ejs': 'ejs' },
    extension: 'ejs'
  }))
  .use(routerResponse())
  .use(router.routes())
  .use(router.allowedMethods())

// logger
// app.use(async (ctx, next) => {
//   const start = new Date()
//   await next()
//   const ms = new Date() - start
//   console.log(`${ctx.method} ${ctx.url} - $ms`)
// })

routes(router)
app.on('error', function (err, ctx) {
  ctx.status = 404
})

module.exports = app.listen(port, () => {
  console.log(`Listening on http://localhost:${port}`)
})
